package com.linh.web.db;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

public class DAOHibernateImpl implements DataAccessObject {

	private SessionFactory sessionFactory;

	public DAOHibernateImpl(SessionFactory sessionFactory) {
		super();
		this.sessionFactory = sessionFactory;
	}

	public  <Entity>void save(Entity e) {
		sessionFactory.getCurrentSession().save(e);

	}

	public <Entity> void delete(Entity e) {
		sessionFactory.getCurrentSession().delete(e);

	}

	@SuppressWarnings("unchecked")
	public <Key,Entity> Entity get(Key id, String idFieldName, Class<Entity> klass) {
		Session session = sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(klass);
		criteria.add(Restrictions.eq(idFieldName, id));
		return (Entity) criteria.uniqueResult();

	}

	@SuppressWarnings("unchecked")
	public <Entity> List<Entity> getAll(Class<Entity> klass) {
		Session session = sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(klass);
		return criteria.list();
	}

}
